<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Document</title>
  </head>
  <body>
    <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
    <script src="./03-javascript-state-machine.js"></script>
    <script>
      // 状态机模型
      var fsm = new StateMachine({
        init: "pending", // 初始化状态
        transitions: [
          {
            name: "resolve", //事件名称
            from: "pending",
            to: "fullfilled",
          },
          {
            name: "reject", //事件名称
            from: "pending",
            to: "rejected",
          },
        ],
        methods: {
          // 成功，监听 resolve
          onResolve: function (state, data) {
            // 参数：state - 当前状态机实例; data - fsm.resolve(xxx) 执行时传递过来的参数
            data.successList.forEach((fn) => fn());
          },
          // 失败，监听 reject
          onReject: function (state, data) {
            // 参数：state - 当前状态机实例; data - fsm.reject(xxx) 执行时传递过来的参数
            data.failList.forEach((fn) => fn());
          },
        },
      });

      // 定义 Promise
      class MyPromise {
        constructor(fn) {
          this.successList = [];
          this.failList = [];

          fn(
            () => {
              // resolve 函数
              fsm.resolve(this);
            },
            () => {
              // reject 函数
              fsm.reject(this);
            }
          );
        }
        then(successFn, failFn) {
          this.successList.push(successFn);
          this.failList.push(failFn);
        }
      }

      // 测试代码
      function loadImg(src) {
        // 刚开始创建 promise 对象时传入的函数会立即执行，在这里面就是
        //   function (resolve, reject) {
        //   var img = document.createElement("img");
        //   img.onload = function () {
        //     resolve(img);
        //   };
        //   img.onerror = function () {
        //     reject();
        //   };
        //   img.src = src;
        // }
        const promise = new MyPromise(function (resolve, reject) {
          var img = document.createElement("img");
          img.onload = function () {
            resolve(img);
          };
          img.onerror = function () {
            reject();
          };
          img.src = src;
        });
        return promise;
      }
      var src = "http://www.imooc.com/static/img/index/logo_new.png";
      var result = loadImg(src);
      console.log(result);

      result.then(
        function (img) {
          console.log("success 1");
        },
        function () {
          console.log("failed 1");
        }
      );
      result.then(
        function (img) {
          console.log("success 2");
        },
        function () {
          console.log("failed 2");
        }
      );
    </script>
  </body>
</html>
